package com.lin.cms.service.impl;


import java.sql.Timestamp;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lin.cms.dao.CmsUserMapper;
import com.lin.cms.dao.RoleMapper;
import com.lin.cms.dao.SiteMapper;
import com.lin.cms.domain.CmsUser;
import com.lin.cms.domain.Role;
import com.lin.cms.domain.Site;
import com.lin.cms.service.CmsUserService;

@Service
public class CmsUserServiceImpl implements CmsUserService {

	public CmsUser selectByPrimaryKey(Integer userId) {
		// TODO Auto-generated method stub
		CmsUser cmsUser=cmsUserMapper.selectByPrimaryKey(userId);
		
		List<Site> sitesList=siteMapper.getSiteByUserId(userId);
		cmsUser.setSites(sitesList);
		
		List<Role> roles = cmsUser.getRoles();
		if (roles == null) {
			cmsUser.setAllPerms(null);
		}
		Set<String> allPerms = new HashSet<String>();
		for (Role role : roles) {
			allPerms.addAll(roleMapper.getRoles(role.getRoleId()).getPerms());
		}
		cmsUser.setAllPerms(allPerms);
		return cmsUser;
	}

	public CmsUser getUserSites(Integer userId) {
		// TODO Auto-generated method stub
		return cmsUserMapper.getUserSites(userId);
	}
	
	public void updateLoginInfo(Integer userId, String ip) {
		// TODO Auto-generated method stub
		Date now = new Timestamp(System.currentTimeMillis());
		CmsUser user = selectByPrimaryKey(userId);
		if (user != null) {
			user.setLoginCount(user.getLoginCount() + 1);
			user.setLastLoginIp(ip);
			user.setLastLoginTime(now);
		}
	}
	
	public List<CmsUser> getAdminList(Integer siteId, Boolean allChannel,
			Boolean disabled, Integer rank) {
		// TODO Auto-generated method stub
		return cmsUserMapper.getAdminList(siteId, allChannel, disabled, rank);
	}
	
	@Autowired
	private CmsUserMapper cmsUserMapper;
	@Autowired
	private SiteMapper siteMapper;
	@Autowired
	private RoleMapper roleMapper;
	
	
}
